package cz.data.domain.visual.service.impl;

import cz.data.domain.metadata.model.MetadataUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.core.DataConstant;
import cz.data.common.support.db.source.DataSourceRegistry;
import cz.data.common.support.db.source.DbQuery;
import cz.data.common.support.db.DbProperty;
import cz.data.common.exception.DataException;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.rpc.MetadataSourceFeign;
import cz.data.domain.visual.dao.ChartDao;
import cz.data.domain.visual.dao.DataSetDao;
import cz.data.domain.visual.mapstruct.ChartMapper;
import cz.data.domain.visual.model.dto.ChartConfig;
import cz.data.domain.visual.model.dto.ChartDto;
import cz.data.domain.visual.model.dto.ChartItem;
import cz.data.domain.visual.model.entity.ChartEntity;
import cz.data.domain.visual.model.entity.DataSetEntity;
import cz.data.domain.visual.service.ChartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ChartServiceImpl extends BaseServiceImpl<ChartDao, ChartEntity> implements ChartService {

    @Autowired
    private ChartDao chartDao;

    @Autowired
    private ChartMapper chartMapper;

    @Autowired
    private DataSetDao dataSetDao;

    @Autowired
    private MetadataSourceFeign metadataSourceFeign;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChartEntity saveChart(ChartDto chartDto) {
        ChartEntity chart = chartMapper.toEntity(chartDto);
        chartDao.insert(chart);
        return chart;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ChartEntity updateChart(ChartDto chartDto) {
        ChartEntity chart = chartMapper.toEntity(chartDto);
        chartDao.updateById(chart);
        return chart;
    }

    @Override
    public ChartEntity getChartById(String id) {
        return super.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChartById(String id) {
        chartDao.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChartBatch(List<String> ids) {
        chartDao.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyChart(String id) {
        ChartEntity chartEntity = Optional.ofNullable(super.getById(id)).orElseThrow(() -> new DataException("获取失败"));
        ChartEntity copy = new ChartEntity();
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        copy.setChartName(chartEntity.getChartName() + "_副本" + format);
        copy.setChartThumbnail(chartEntity.getChartThumbnail());
        copy.setChartConfig(chartEntity.getChartConfig());
        copy.setStatus(DataConstant.EnableState.ENABLE.getKey());
        chartDao.insert(copy);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buildChart(ChartDto chartDto) {
        ChartEntity chart = chartMapper.toEntity(chartDto);
        chartDao.updateById(chart);
    }

    @Override
    public Map<String, Object> dataParser(ChartConfig chartConfig) {
        String datasetId = chartConfig.getDataSetId();
        DataSetEntity dataSetEntity = Optional.ofNullable(dataSetDao.selectById(datasetId)).orElseThrow(() -> new DataException("获取数据集失败"));
        MetadataSourceEntity metadataSourceEntity = Optional.ofNullable(metadataSourceFeign.getMetadataSourceById(dataSetEntity.getSourceId())).orElseThrow(() -> new DataException("获取数据源失败"));
        DbProperty dbQueryProperty = MetadataUtil.dbProperty(metadataSourceEntity);
        DbQuery dbQuery = Optional.ofNullable(DataSourceRegistry.factory(metadataSourceEntity.getDbType()))
                .map(factory -> factory.createDbQuery(dbQueryProperty))
                .orElseThrow(() -> new DataException("不支持的数据库类型"));

        List<ChartItem> rows = chartConfig.getRows();
        List<ChartItem> columns = chartConfig.getColumns();
        List<ChartItem> measures = chartConfig.getMeasures();
        String setSql = dataSetEntity.getSetSql();
        StringBuilder sql = new StringBuilder();
        List<ChartItem> groups = new ArrayList<>();
        groups.addAll(rows);
        groups.addAll(columns);
        sql.append("SELECT");
        String groupJoining = null;
        String measureJoining = null;
        if (CollectionUtils.isNotEmpty(groups)) {
            groupJoining = groups.stream().map(ChartItem::getCol).collect(Collectors.joining(", ", " ", " "));
            sql.append(groupJoining);
        }
        if (CollectionUtils.isNotEmpty(measures)) {
            if (StringUtils.isNotBlank(groupJoining)) {
                sql.append(",");
            } else {
                sql.append(" ");
            }
            measureJoining = measures.stream().map(s -> new StringBuilder().append(s.getAggregateType()).append("(").append(s.getCol()).append(") AS ").append(s.getCol())).collect(Collectors.joining(", ", " ", " "));
            sql.append(measureJoining);
        }
        sql.append("FROM (").append(setSql).append(") TEMP_VIEW");
        if (CollectionUtils.isNotEmpty(groups)) {
            sql.append(" GROUP BY ").append(groups.stream().map(ChartItem::getCol).collect(Collectors.joining(", ")));
        }
        List<Map<String, Object>> data = dbQuery.queryList(sql.toString());
        Map<String, Object> map = new HashMap<>(2);
        map.put("data", data);
        map.put("sql", sql.toString());
        return map;
    }
}
